package cz.data.domain.metadata.explore;

import cz.data.common.support.db.core.DbColumn;
import cz.data.common.support.db.core.DbTable;
import cz.data.domain.driver.rpc.IDriverFeign;
import cz.data.domain.metadata.model.entity.MetadataColumnEntity;
import cz.data.domain.metadata.model.entity.MetadataSourceEntity;
import cz.data.domain.metadata.model.entity.MetadataTableEntity;
import cz.data.domain.metadata.model.enums.SyncStatus;
import cz.data.domain.metadata.service.RemoteDriverService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Component
public class RemoteDriverMetadataExplore extends AbstractMetadataExplore {
    @Resource
    RemoteDriverService remoteDriverService;

    @Override
    public MetadataSourceEntity explore(MetadataSourceEntity dataSource) {
        String sourceId = dataSource.getId();
        IDriverFeign driverFeign = remoteDriverService.getDriverFeign(dataSource.getDbType());
        List<DbTable> tables = driverFeign.getSourceAllTable(sourceId);
        if (CollectionUtils.isNotEmpty(tables)) {
            List<MetadataTableEntity> metadataTables = convertTables(tables, sourceId);
            for (MetadataTableEntity table : metadataTables) {
                super.refreshTable(table);
                List<DbColumn> columns = driverFeign.getSourceTableColumns(sourceId, table.getTableName());
                List<MetadataColumnEntity> metadataColumnEntityList = convertColumns(columns, sourceId, table.getId());
                metadataColumnEntityList.forEach(super::refreshColumn);
            }
        }
        dataSource.setIsSync(SyncStatus.IsSync.getKey());
        return dataSource;
    }

}
